﻿using System.Security.Cryptography;
using System.Text;

namespace Rj.PersonnelVerification.Server.Utils
{
    public class CryptoHelper
    {
        // MD5加密（哈希，不可逆）
        public static string MD5Encrypt(string input)
        {
            //using (MD5 md5 = MD5.Create())
            //{
            //    byte[] inputBytes = Encoding.UTF8.GetBytes(input);
            //    byte[] hashBytes = md5.ComputeHash(inputBytes);

            //    // 将字节数组转换为16进制字符串
            //    StringBuilder sb = new StringBuilder();
            //    for (int i = 0; i < hashBytes.Length; i++)
            //    {
            //        sb.Append(hashBytes[i].ToString("x2"));
            //    }
            //    return sb.ToString();
            //}

            string returnstr = string.Empty;
            if (string.IsNullOrEmpty(input))
            {
                return returnstr;
            }

            if (input.Trim().Length < 32)
            {
                var md5 = new MD5CryptoServiceProvider();
                var result = Encoding.Default.GetBytes(input.Trim());
                var output = md5.ComputeHash(result);

                returnstr = output.Aggregate(string.Empty, (current, put) => current + put.ToString("X"));
            }
            else
            {
                var output = HexStrTobyte(input);
                returnstr = output.Aggregate(string.Empty, (current, put) => current + put.ToString("X"));
            }
            return returnstr;
        }

        private static byte[] HexStrTobyte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
            return returnBytes;
        }

        // AES加密（对称加密）
        public static string AESEncrypt(string plainText, string key)
        {
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Encoding.UTF8.GetBytes(GetValidKey(key));
                aesAlg.IV = new byte[16];  // 初始化为0的IV向量

                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            swEncrypt.Write(plainText);
                        }
                        byte[] encrypted = msEncrypt.ToArray();
                        return Convert.ToBase64String(encrypted);
                    }
                }
            }
        }

        // AES解密
        public static string AESDecrypt(string cipherText, string key)
        {
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Encoding.UTF8.GetBytes(GetValidKey(key));
                aesAlg.IV = new byte[16];  // 初始化为0的IV向量

                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(cipherText)))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {
                            return srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
        }

        // 获取合法的AES密钥（确保长度为16字节）
        private static string GetValidKey(string key)
        {
            if (key.Length < 16)
            {
                key = key.PadRight(16, '0'); // 如果key长度小于16，则补充0
            }
            else if (key.Length > 16)
            {
                key = key.Substring(0, 16);  // 如果key长度大于16，则截断
            }
            return key;
        }
    }
}
